import requests
import os
from lxml import etree
import re

# 获取视频名称
name_url = input("请输入视频url:")
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
}
html = requests.get(url=name_url, headers=headers).text
title = etree.HTML(html).xpath('/html/body/div[2]/div[2]/div[1]/div[1]/h1/text()')[0].split()
title_name = '_'.join(title)
print(title_name)

# 获取视频音频url
url_str = etree.HTML(html).xpath('//script[contains(text(),"window.__playinfo__")]/text()')[0]
video_url = re.findall(r'"video":\[{"id":\d+,"baseUrl":"(.*?)",', url_str)[0]
print(video_url)
audio_url = re.findall(r'"audio":\[{"id":\d+,"baseUrl":"(.*?)",', url_str)[0]
print(audio_url)

# 获取视频音频文件
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
    'Referer': name_url
}
video_res = requests.get(video_url, headers=headers)
audio_res = requests.get(audio_url, headers=headers)

data_video = video_res.content
data_audio = audio_res.content

with open(title_name + '_纯视频.mp4', 'wb') as f:
    f.write(data_video)

with open(title_name + '_纯音频.mp3', 'wb') as f:
    f.write(data_audio)
# 合成视频
os.system('ffmpeg -i "{}" -i "{}" -c copy "{}" '.format(title_name + '_纯视频.mp4', title_name + '_纯音频.mp3',
                                                        title_name + '.mp4'))
# 移除中间过程文件
os.remove(title_name + '_纯视频.mp4')
os.remove(title_name + '_纯音频.mp3')